package com.liang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//sqlSessionFactory ---> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        String resource = "mybatis-config.xml";
        try {
            //获取sqlSessionFactory
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //有了sqlSessionFactory工厂，我们就可以从中获取sqlSession对象实例，该对象
        //包含了面向数据库执行SQL命令所需的所有方法
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
     //自动提交
    public static SqlSession getSqlSessionAuto() {
        return sqlSessionFactory.openSession(true);
    }
}